package com.github.prontera.service;

import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.prontera.Shift;
import com.github.prontera.StatusCode;
import com.github.prontera.domain.Activity;
import com.github.prontera.domain.Client;
import com.github.prontera.domain.ClientActivity;
import com.github.prontera.persistence.ActivityMapper;
import com.github.prontera.persistence.ClientActivityMapper;
import com.github.prontera.persistence.CrudMapper;

/**
 * 活动
 */
@Service
public class ActivityService extends CrudServiceImpl<Activity>{
    
    @Autowired
    private ClientActivityMapper clientActivityMapper;
    @Autowired
	private ActivityMapper mapper;
    
  	@Autowired
    public ActivityService(CrudMapper<Activity> mapper) {
        super(mapper);
    }
  	
  	public List<Activity> findClientActivity(Long clientId){
  		Activity activity=new Activity();
  		activity.setClientId(clientId);
  		return mapper.findClientActivity(activity);
  	}
  	
  	public List<Client> findActivityClients(Activity activity){
  		return mapper.findActivityClients(activity);
  	}
  	
  	public Integer updateActivityStatus(){
  		return mapper.updateActivityStatus();
  	}
  	
  	
  	/**
  	 * 参与活动
  	 */
  	@Transactional(propagation = Propagation.REQUIRED)
  	public boolean buyActivity(Long id,Integer buyCount,Long clientId,BigDecimal payAmount) {
		Activity updateActivity=new Activity();
		updateActivity.setId(id);
		updateActivity.setBuyNumber(buyCount);
		if(mapper.updateStock(updateActivity)>0) {//更新已购买量成功
			ClientActivity insertClientActivity=new ClientActivity();
			insertClientActivity.setActivityId(id);
			insertClientActivity.setClientId(clientId);
			insertClientActivity.setPayAmount(payAmount);
			insertClientActivity.setPayTime(OffsetDateTime.now());
			if(clientActivityMapper.insert(insertClientActivity)<=0) {
				Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "参数错误,售后再试");
			}
		}else {
			Shift.fatal(StatusCode.INSUFFICIENT_STOCK, "该商品已罄售");
		}
  		return true;
	}

	public List<Activity> find2(Activity activity) {
		return mapper.find2(activity);
	}

}
